//+---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation, 2008
//
// File: DataPointSchemaHelper.cs
//
// Contents: Helper factory class for creating DataPointSchema class
//
// Created by: Adam Wardynski (AdamWa) 2/4/2008
//
//----------------------------------------------------------------------------
using System;
using System.Xml;
using System.Collections.Generic;
using System.Configuration;

namespace Microsoft.Reputation.Services
{
    internal class DataPointSchemaHelper : IConfigurationSectionHandler
    {
        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, XmlNode section)
        {
            // first get delimiter (if it exists)
            char delimiter = '\t';
            if (section.Attributes.Count == 1)
            {
                object o = section.Attributes["delimiter"];
                if (o != null)
                {
                    delimiter = Char.Parse(section.Attributes["delimiter"].Value);
                }
            }

            // get all dataPointElement children
            XmlNodeList elements = section.SelectNodes("DataPointElements/DataPointElement");
            DataPointSchemaElement schemaElement;
            string name;
            DataPointType type;
            int ordinal;
            bool required;
            List<DataPointSchemaElement> al = new List<DataPointSchemaElement>(elements.Count);
            Dictionary<String, DataPointSchemaElement> ht = new Dictionary<string, DataPointSchemaElement>(elements.Count);

            // iterate through all dataPointElements
            foreach (XmlNode element in elements)
            {
                // pull out name, type, ordinal, and required attributes
                name = element.Attributes["name"].Value;
                type = (DataPointType)Enum.Parse(typeof(DataPointType), element.Attributes["type"].Value, true);
                ordinal = Int32.Parse(element.Attributes["ordinal"].Value);
                required = Boolean.Parse(element.Attributes["required"].Value);

                // create a new DataPointSchemaElement to hold the info
                // this ctor does all the need validation
                schemaElement = new DataPointSchemaElement(name, type, ordinal, required);

                // add the DataPointSchemaElement to the two collections
                ht.Add(name, schemaElement);
                al.Insert(ordinal, schemaElement);
            }

            // create adn return the finished DataPointSchema
            return new DataPointSchema(ht, al, delimiter, section.InnerXml);
        }

        #endregion
    }
}